/**create by liuhua at 2019年8月20日 下午4:44:17**/
package com.star.truffle.common.dto;

import java.util.List;

import javax.validation.constraints.NotEmpty;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Base64Utils;

import com.star.truffle.core.StarServiceException;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
public class ImageBase64UploadRequestDto {

  @NotEmpty(message = "图片必填")
  private List<Image> images;

  @Data
  public static class Image {
    @ApiModelProperty(value = "是否需要水印 1是")
    private Integer mark;
    @ApiModelProperty(value = "是否需要压缩 1是")
    private Integer shrink;
    @ApiModelProperty(value = "允许上传的图片宽度 像素")
    private Integer width;
    @ApiModelProperty(value = "允许上传的图片高度 像素")
    private Integer height;
    @ApiModelProperty(value = "允许上传的图片最大宽度 像素")
    private Integer maxWidth;
    @ApiModelProperty(value = "允许上传的图片最大高度 像素")
    private Integer maxHeight;
    @ApiModelProperty(value = "文件名是否已源文件名存储")
    private Integer of;
    @ApiModelProperty(value = "文件名")
    private String fileName;
    @ApiModelProperty(value = "文件名内容 base64")
    private String image;

    public String getSuffix() {
      String dataPrix = "";
      if (StringUtils.isBlank(image)) {
        throw new StarServiceException("上传失败，上传图片数据为空");
      } else {
        String[] d = image.split("base64,");
        if (d != null && d.length == 2) {
          dataPrix = d[0];
        } else {
          throw new StarServiceException("上传失败，数据不合法");
        }
      }
      String suffix = "";
      if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {// 编码的jpeg图片数据
        suffix = ".jpg";
      } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {// 编码的icon图片数据
        suffix = ".ico";
      } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {// 编码的gif图片数据
        suffix = ".gif";
      } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {// 编码的png图片数据
        suffix = ".png";
      } else {
        throw new StarServiceException("上传图片格式不合法");
      }
      return suffix;
    }
    
    public byte[] getData() {
      String data = "";
      if (StringUtils.isBlank(image)) {
        throw new StarServiceException("上传失败，上传图片数据为空");
      } else {
        String[] d = image.split("base64,");
        if (d != null && d.length == 2) {
          data = d[1];
        } else {
          throw new StarServiceException("上传失败，数据不合法");
        }
      }
      byte[] bs = Base64Utils.decodeFromString(data);
      return bs;
    }
  }
}
